package vashion.azeroth.back.controller.tran;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import vashion.azeroth.back.controller.base.BaseController;
import vashion.azeroth.back.core.context.BackUserContext;
import vashion.azeroth.common.common.check.FormatCheck;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.contant.MemberErrorEnum;
import vashion.azeroth.core.manager.personal.PersonalInviteCodeManager;
import vashion.azeroth.core.manager.personal.PersonalMemberManager;
import vashion.azeroth.core.personal.pojo.PersonalInviteCode;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.base.BaseService;

/**
 * 用户管理页面
 */
@Controller
@RequestMapping("/back/member")
public class UserManagerController extends BaseController {

	@Autowired
	protected BackUserContext userContext;

	@Autowired
	private PersonalMemberManager personalMemberManager;

	@Autowired
	private PersonalInviteCodeManager personalInviteCodeManager;

	/**
	 * 查询用户列表
	 *
	 * @param member
	 * @return 符合条件的用户的页面
	 */
	@RequestMapping("getMemberList.htm")
	public String getMemberList(Model model, @ModelAttribute("member") PersonalMember member,
			HttpServletRequest request) {

		if (member.getPageNum() <= 0) {
			member.setPageNum(1);
		}
		member.setFirstRow((member.getPageNum() - 1) * member.getPageSize());
		PersonalMember memberQuery = new PersonalMember();
		memberQuery.setMemberName(member.getMemberName());
		memberQuery.setNickName(member.getNickName());
		memberQuery.setType(member.getType());
		memberQuery.setPageNum(member.getPageNum());
		memberQuery.setFirstRow(member.getFirstRow());
		memberQuery.setPageSize(member.getPageSize());
		List<PersonalMember> memberList = personalMemberManager.find(memberQuery);
		// 设置可用验证码数量
		for (PersonalMember memberTemp : memberList) {
			if (AzerothConstants.PersonalMember.MemberType.supplier == memberTemp.getType()) {
				PersonalInviteCode inviteCodeParam = new PersonalInviteCode();
				inviteCodeParam.setMemberId(memberTemp.getMemberId());
				inviteCodeParam.setStatus(AzerothConstants.PersonalInviteCode.PersonalInviteCodeStatus.unused);
				int availableInviteCodeCount = personalInviteCodeManager.findCnt(inviteCodeParam);
				memberTemp.setAvailableInviteCodeCount(availableInviteCodeCount);
			} else {
				memberTemp.setAvailableInviteCodeCount(0);
			}
		}
		int memberCount = personalMemberManager.findCnt(memberQuery);
		BaseService page = new BaseService();
		page.initPages(memberQuery, memberCount);
		model.addAttribute("memberList", memberList);
		model.addAttribute("member", memberQuery);
		model.addAttribute("page", page);

		return "/member/memberList";
	}

	/**
	 * 前往生成供应商账号页面
	 * 
	 * @param member
	 * @return
	 */
	@RequestMapping("gotoGenerateProviderAccountPage.htm")
	public String gotoGenerateProviderAccountPage(Model model, @ModelAttribute("member") PersonalMember member,
			HttpServletRequest request) {
		return "/member/generateProviderAccount";
	}

	/**
	 * 注册接口
	 * 
	 * @param member
	 * @return
	 */
	@RequestMapping("generateProviderAccount.htm")
	public String generateProviderAccount(Model model, @ModelAttribute("member") PersonalMember member,
			HttpServletRequest request) {

		String errorMsg = "";
		model.addAttribute("memberName", member.getMemberName());
		//检查格式
		if (StringUtils.isBlank(member.getMemberName())) {
			errorMsg += "用户名" + GenericErrorEnum.NOT_EMPTY.getErrorMessage() + "。";
		}

		if (!FormatCheck.isMobile(member.getMemberName())) {
			errorMsg += "用户名" + GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorMessage() + "。";
		}

		if (StringUtils.isBlank(member.getMemberPwd())) {
			errorMsg += "密码" + GenericErrorEnum.NOT_EMPTY.getErrorMessage() + "。";
		}

		if (!FormatCheck.isLegalPassword(member.getMemberPwd())) {
			errorMsg += "密码" + GenericErrorEnum.PARAM_FORMAT_ERROR.getErrorMessage() + "。";
		} 
		if (StringUtils.isBlank(errorMsg)) {
			// 查询用户是否已存在
			PersonalMember resultMember = personalMemberManager.getMemberByName(member.getMemberName());
			if (null != resultMember) {
				errorMsg += MemberErrorEnum.EXIXTID.getErrorMessage() + "。";
			} else {
				PersonalMember generatedProvider = new PersonalMember();
				BeanUtils.copyProperties(member, generatedProvider);
				generatedProvider = personalMemberManager.generateProviderAccount(generatedProvider,
						getLoginUserId(request));
				if (null != generatedProvider && null != generatedProvider.getMemberId()
						&& 0 < generatedProvider.getMemberId()) {
					model.addAttribute("addResult", true);
					model.addAttribute("member", new PersonalMember());
				} else {
					errorMsg += GenericErrorEnum.SYSTEM_ERROR.getErrorMessage() + "。";
				}
			}
		}
		if (!StringUtils.isBlank(errorMsg)) {
			model.addAttribute("addResult", false);
			model.addAttribute("member", member);
			model.addAttribute("errorMsg", errorMsg);
		}
		return "/member/generateProviderAccount";
	}

	/**
	 * 冻结一个用户账号
	 * 
	 * @param member
	 * @param request
	 * @return 冻结的结果
	 */
	@RequestMapping("freezeMember.htm")
	public ModelAndView freezeMember(Model model, @ModelAttribute("member") PersonalMember member,
			HttpServletRequest request) {
		ApiResult<Boolean> freezeResult = personalMemberManager.freezeMember(member.getMemberId(),
				getLoginUserId(request));

		if (freezeResult.isSuccess() && freezeResult.getData()) {
			return new ModelAndView("forward:getMemberList.htm");
		} else {
			return null;
		}
	}

	/**
	 * 恢复一个用户账号
	 * 
	 * @param member
	 * @param request
	 * @return 恢复的结果
	 */
	@RequestMapping("resumeMember.htm")
	public ModelAndView resumeMember(Model model, @ModelAttribute("member") PersonalMember member,
			HttpServletRequest request) {
		ApiResult<Boolean> resumeResult = personalMemberManager.resumeMember(member.getMemberId(),
				getLoginUserId(request));

		if (resumeResult.isSuccess() && resumeResult.getData()) {
			return new ModelAndView("forward:getMemberList.htm");
		} else {
			return null;
		}
	}
	
	@RequestMapping("getMember.htm")
	public String getMember(Model model, Long memberId) {
		PersonalMember member = personalMemberManager.get(memberId);

		model.addAttribute("member", member);
        return "/member/modifyMember"; 
	}
	
	@RequestMapping("gotoUpdateItemsStockPage.htm")
	public String gotoUpdateItemsStockPage(Model model, @ModelAttribute("member") PersonalMember member) {
		model.addAttribute("member", member);
        return "/member/batchUpdateItemsStock"; 
	}
	
	@RequestMapping("memberModify.htm")
    @ResponseBody
    public ApiResult<String> memberModify(@ModelAttribute("member") PersonalMember member) {
		
		member.setTimeEdit(new Date());
		personalMemberManager.update(member);
		
    	return ApiResult.newSuccessResult();
    }

}
